<template>
    <el-button type="primary" :disabled="disabled" @click="sendCode" v-bind="$attrs" v-on="$listeners">{{text}}</el-button>
</template>
<script>
    import api from "@/api/index"
    export default {
        name:"VerificationButton",
        props:["phone"],
        data(){
            return {
                initTime:60,
                timer:undefined,
                disabled:false,
                text:"获取验证码"
            }
        },
        methods:{
            sendCode(){
                this.disabled = true;
                if(!this.phone){
                    this.msgError("请输入手机号!");
                    return
                }
               // this.changeNum()
                api.sendSms(this.phone).then(()=>{
                    this.msgSuccess("发送成功！")
                    this.changeNum()
                }).finally(()=>{
                  this.disabled = false;
                })
            },
            changeNum(){
                // 3 禁用input
                this.text = this.initTime + 's后重新获取'
                this.initTime--;
                // 5 判断是否为0s,则清除定时器,取消input的禁用
                if (this.initTime <= 0) {
                    clearTimeout(this.timer);
                    this.text= '重新获取'
                    this.disabled = false;
                    this.initTime = 60
                }else{
                  this.timer = setTimeout(()=> {
                    this.changeNum()
                  }, 1000)
                }
            }
        }
    }
</script>
